package com.zzyl.framework.interceptor;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.zzyl.common.core.domain.model.LoginUser;
import com.zzyl.common.utils.SecurityUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;

//@Component
//public class MyMetaObjectHandler implements MetaObjectHandler {
//
//    @Override
//    public void insertFill(MetaObject metaObject) {
//        this.strictInsertFill(metaObject, "createTime", Date.class, new Date());
//        this.strictInsertFill(metaObject, "createBy", String.class, loadUserId()+"");
//    }
//
//    @Override
//    public void updateFill(MetaObject metaObject) {
//        Object userId = loadUserId();
//        if (userId == null) {
//            userId = "system"; // 设置默认用户ID
//        }
//        this.strictUpdateFill(metaObject, "updateBy", String.class, userId.toString());
//    }
//
//
//    /**
//     * 获取当前登录人的ID
//     * @return
//     */
//    public static Long loadUserId(){
//        //获取当前登录人的id
//        LoginUser loginUser = SecurityUtils.getLoginUser();
//        if(ObjectUtils.isNotEmpty(loginUser)){
//            return loginUser.getUserId();
//        }
//        return 1L;
//    }
//}
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
    @Autowired
    private HttpServletRequest request;

    public boolean isExclude() {
        try {
            String requestURI = request.getRequestURI();
            if (requestURI.startsWith("/member")) {
                return false;
            }
            return true;
        } catch (Exception e) {
            return true;
        }
    }

    @Override
    public void insertFill(MetaObject metaObject) {
        Date now = new Date();
        this.strictInsertFill(metaObject, "createTime", Date.class, now);
        if (!isExclude()) {
            this.strictInsertFill(metaObject, "createBy", String.class, loadUserId());
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        this.strictUpdateFill(metaObject, "updateTime", Date.class, new Date());
        if (!isExclude()) {
            this.strictUpdateFill(metaObject, "updateBy", String.class, loadUserId());
        }

    }

    /**
     * 获取当前登录人的ID
     *
     * @return 用户ID或系统默认ID
     */
    public static String loadUserId() {
        try {
            LoginUser loginUser = SecurityUtils.getLoginUser();
            if (ObjectUtils.isNotEmpty(loginUser) && loginUser.getUserId() != null) {
                return loginUser.getUserId().toString();
            }
        } catch (Exception e) {
            // 忽略异常，使用默认值
        }
        return "1"; // 系统默认用户ID
    }
}
